<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {

	private $errormsg='';
	private $checkkey='ucheckcode';

	function __construct(){
		parent::__construct();
		$this->Lang_model->loadLang('admin');
	}
	
	public function login(){
		$post = $this->input->post(NULL,TRUE);
		if($post['opt']=='ajax'){
			if($this->validCode($post) !== TRUE){
				echo 'error';exit;
			}
			$this->load->model('User_model');
			$username = trim($post['user_name']);
			$userpass = trim($post['user_pass']);
			if($this->User_model->login($username,$userpass)){
				echo 'ok';exit;
			}else{
				echo 'error';exit;
			}
		}
		$this->load->view('login.php');
	}
	
	public function index()
	{
		$post = $this->input->post(NULL,TRUE);
		if(!empty($post)){
			if($this->validCode($post) !== TRUE){
				echo $this->errormsg;exit;
			}
			$this->load->model('User_model');
			$username = trim($post['user_name']);
			$userpass = trim($post['user_pass']);
			if($this->User_model->login($username,$userpass)){
				echo 'ok';exit;
			}else{
				echo 'error';exit;
			}
		}else{
			$this->load->view('login');
		}
	}
	
	public function ajaxlogin(){
		$post = $this->input->post(NULL,TRUE);
		if(!empty($post)){
			if($this->validCode($post) !== TRUE){
				echo $this->errormsg;exit;
			}
			$username = trim($post['user_name']);
			$userpass = trim($post['user_pass']);
			if($this->User_model->login($username,$userpass)){
				show_jsonmsg(200);
			}else{
				show_jsonmsg(204);
			}
		}else{
			$remsg = $this->load->view('ajaxlogin','',true);
			show_jsonmsg(200,$remsg);
		}
	}
	
	public function lose(){
		$this->load->vars('lose',1);
		$this->load->view('login');
	}

	public function logout(){
		$this->load->model('User_model');
		$this->User_model->logout();
		redirect(site_aurl('login'));
	}

	//验证码
	public function checkcode(){
		$this->load->helper('checkcode');
		$str = "23456789abcdefghijkmnpqrstuvwxyz";
		$code = '';
		for ($i = 0; $i < 4; $i++) {
			$code .= $str[mt_rand(0, strlen($str)-1)];
		}
		$this->session->set_userdata($this->checkkey,$code);
		getCode($code,28);
		exit;
	}

	/**
	 * 验证码
	 */
	function validCode($post){
		if(empty($post['checkcode'])){
			$this->errormsg=lang('checkcode_empty');
			return FALSE;
		}
		$scode=$this->session->userdata($this->checkkey);
		if(empty($scode)){
			$this->errormsg=lang('checkcode_exprised');
			return FALSE;
		}
		$this->_destroycode();
		if(strcasecmp($scode, $post['checkcode'])=== 0) {
			return TRUE;
		}else{
			$this->errormsg=lang('checkcode_error');
			return FALSE;
		}
	}

	//销毁验证码
	function _destroycode(){
		$this->session->unset_userdata($this->checkkey);
	}
}